var express = require('express');
var router = express.Router();
var connection = require('../db/sql');
// 引入促销商品的sql
var IndexGoods = require("../db/IndexGoods")

// 引入七牛依赖
var qiniu = require('qiniu')

// 用于给token解码
const jwt_decode = require('jwt-decode');

// 引入user的sql
var user = require("../db/userSql")

//验证码
let code = '';
//接入短信的sdk
var QcloudSms = require("qcloudsms_js");

// 引入支付宝沙箱
const alipaySdk = require('../db/alipay.js');
const AlipayFormData = require('alipay-sdk/lib/form').default;

// 设置允许跨域
const cors = require("cors");
const { error, count } = require('console');
router.use(cors());

/* GET home page. */
router.get('/', function(req, res, next) {
	res.render('index', {
		title: 'Express'
	});
});
// 客户端 调用接口，生成七牛token
router.post('/api/storeToken', function(req, res, next) {
	let accessKey = 'qUGpMbu--mVxHrgNmOmqx3n7PtvBcnUwLSbQUC8o';
	let secretKey = 'wf8uddjj_C4N2NP88zDF3-Pet4-X4FynUruQx9PD';
	let bucket = 'myshop1235';
	let mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
	
	let options = {
		scope: bucket, //七牛云目录资源
		expires: 3600 * 24
	};
	let putPolicy = new qiniu.rs.PutPolicy(options);
	let uploadToken = putPolicy.uploadToken(mac);
	res.send({
		code:0,
		succecc:true,
		data:uploadToken
	})
});

// 促销商品
router.get('/api/home/getDiscountGoods', function(req, res, next) {
	// 前端返回的参数
	let param = {
		isDiscount: req.body.isDiscount
	}
	connection.query(IndexGoods.queryDiscountGoods(param), function(error, results, fields) {
		res.send({
			data: {
				succecc: true,
				msg: "数据请求成功",
				data: results
			}
		})
	})
});
// 热销商品
router.get('/api/home/getHotGoods', function(req, res, next) {
	// 前端返回的参数
	let param = {
		isDiscount: req.body.isDiscount
	}
	connection.query(IndexGoods.queryHotGoods(param), function(error, results, fields) {
		res.send({
			data: {
				succecc: true,
				msg: "数据请求成功",
				data: results
			}
		})
	})
});
// 猜你喜欢
router.get('/api/home/getRecommendGoods', function(req, res, next) {
	// 前端返回的参数
	let param = {
		isDiscount: req.body.isDiscount
	}
	connection.query(IndexGoods.queryRecommendGoods(param), function(error, results, fields) {
		res.send({
			data: {
				succecc: true,
				msg: "数据请求成功",
				data: results
			}
		})
	})
});

// 搜索页面数据
router.get('/api/goods/search', function(req, res, next) {
	// desc降序 asc升序
	// 获取对象的值key  前端传递过来的参数
	let [goodsName, orderName] = Object.keys(req.query);
	// name参数的值
	let name = req.query.name
	let order = req.query[orderName]
	// order by 用于对结果集进行排序
	connection.query("select * from search_goods where name like '%" + name + "%' order by " + orderName + " " +
		order + "",
		function(error, results, fields) {
			if (error) throw error;
			res.json({
				code: '0',
				data: results
			})
		})
});
//详情页面数据
router.get('/api/detial/getDetialData', function(req, res, next) {
	let id = req.query.id;
	let shopType = '';
	if(!req.query.shopType){
		shopType =' recommendgoods'
	}else {
		shopType = req.query.shopType;
	}
	connection.query("select * from "+shopType+" where id=" + id + "", function(error, results, fields) {
		if (error) throw error;
		res.send({
			code: "0",
			msg: "数据请求成功",
			data: results
		})
	});
});

//第三方登录
router.post('/api/loginother', function(req, res, next) {
	//前端给后端的数据
	let params = {
		provider:req.body.provider,//登录方式
		openid:req.body.openid,//用户身份id
		nickName:req.body.nickName,//用户昵称
		avatarUrl:req.body.avatarUrl//用户头像
	};
	//查询数据库中有没有此用户
	connection.query( user.queryUserName( params ) , function (error, results, fields) {
		if( results.length > 0){
			//数据库中存在      : 读取
			connection.query( user.queryUserName( params ) , function (e, r) {
				res.send({
					data:r[0]
				})
			})
		}else{
			//数据库中[不]存在  : 存储 ==>读取
			connection.query( user.insertData( params ) , function (er, result) {
				connection.query( user.queryUserName( params ) , function (e, r) {
					res.send({
						data:r[0]
					})
				})
			})
		}
	})
	
})
 
// 用户登录
router.post('/api/login', function(req, res, next) {
	// 前端给后端的数据
  let params = {
	  userName:req.body.userName,
	  userPwd:req.body.userPwd,  
  }
  // 查询用户名或者手机号存在不存在
  connection.query(user.queryUserName(params),function(error,results,fields){
	  if(results.length > 0){
		  connection.query(user.queryUserPwd(params),function(err,result){
			  if(result.length > 0){
				  res.send({
					  data:{
						  success:true,
						  msg:"登录成功",
						  data:result[0]
					  }
				  })
			  }
		  })
	  }else{
		  res.send({
			  data:{
				  success:false,
				  msg:'用户名或手机号不存在'
			  }
		  })
	  }
  })
});
// 添加二级分类
router.post('/api/insertSencodeList',function(req,res,next){
	// 前端传递过啊里的数据
	let token = req.headers.token;
	let phone = jwt_decode(token);
	let list_id = req.body.list_id
	let shop_name = req.body.shop_name;
	let shop_img = req.body.shop_img;
	
	connection.query(`INSERT INTO second_list (first_id, name, imgUrl)VALUES ('${list_id}', '${shop_name}', '${shop_img}')`,function(err,result){
		res.send({
			code:0,
			success:true,
			data:result
		})
	})
})
// 用户修改密码
router.post('/api/updatePwd', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let old_pwd = req.body.old_pwd
	let new_pwd=req.body.new_pwd;
	let def_pwd=req.body.def_pwd;
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id;
		let pwd = results[0].userPwd
		if(old_pwd != pwd){
			res.send({
				code:0,
				succecc:false,
				msg:'输入的旧密码不正确'
			})
		}else{
			connection.query(`update user set userPwd = '${new_pwd}' where id = '${userId}'`,function(err,result){
				res.send({
					code:0,
					succecc:true,
					data:result
				})
			})
		}
	})
})
// 修改用户信息
router.post('/api/Edituser',function(req,res,next){
	// 前端传递过啊里的数据
	let token = req.headers.token;
	let phone = jwt_decode(token);
	let	userName = req.body.userName;
	let	userPwd = req.body.userPwd;
	let	nickName = req.body.nickName;
	let	avatarUrl = req.body.imgUrl;
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id;
		connection.query(`update user set userName = '${userName}',userPwd = '${userPwd}',nickName = '${nickName}',imgUrl = '${avatarUrl}' where id = ${userId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 设置用户 姓名  密码，昵称 数据库中增加一条信息
router.post('/api/adduser',function(req,res,next){
	// 前端传递过啊里的数据
	let params = {
		userName:req.body.userName,
		userPwd:req.body.userPwd,
		nickName:req.body.nickName,
		avatarUrl:req.body.imgUrl,
		phone:req.body.phone,
		userCode:req.body.code,
	}
	if(  params.userCode   ){
		connection.query( user.insertData( params ) , function (error, results, fields) {
			res.send({
				data:{
					success:true,
					msg:"注册成功",
					data:params
				}
			})
		})
	}
	
})
//发送验证码
router.post('/api/code', function(req, res, next) {
	//前端给后端的数据
	let params = {
		userName : req.body.phone
	};
	res.json({
		code:0,
		succecc:true,
		msg:'请求成功！',
		data:params.userName
	})
	// // 短信应用 SDK AppID
	// var appid = 1400187558;  // SDK AppID 以1400开头
	// // 短信应用 SDK AppKey
	// var appkey = "dc9dc3391896235ddc2325685047edc7";
	// // 需要发送短信的手机号码
	// var phoneNumbers = [params.userName];
	// // 短信模板 ID，需要在短信控制台中申请
	// var templateId = 298000;  // NOTE: 这里的模板ID`7839`只是示例，真实的模板 ID 需要在短信控制台中申请
	// // 签名
	// var smsSign = "三人行慕课";  // NOTE: 签名参数使用的是`签名内容`，而不是`签名ID`。这里的签名"腾讯云"只是示例，真实的签名需要在短信控制台申请
	// // 实例化 QcloudSms
	// var qcloudsms = QcloudSms(appid, appkey);
	// // 设置请求回调处理, 这里只是演示，用户需要自定义相应处理回调
	// function callback(err, ress, resData) {
	//   if (err) {
	//       console.log("err: ", err);
	//   } else {
	// 	  code = ress.req.body.params[0];
	//       res.send({
	// 		  data:{
	// 			  success:true,
	// 			  code:code
	// 		  }
	// 	  })
	//   }
	// }
	// var ssender = qcloudsms.SmsSingleSender();
	// var paramss = [  Math.floor( Math.random()*(9999-1000))+1000 ];//发送的验证码
	// ssender.sendWithParam("86", phoneNumbers[0], templateId,
	// paramss, smsSign, "", "", callback); 
	// https://gitee.com/struggle-programming/myShop
	
})

//客户点击商家查看商家商品
router.post('/api/getStoreShop', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let type = req.body.type
	let shopId = req.body.shopId
	let storeName = req.body.storeName
	if(shopId){
		connection.query(`select * from discountgoods where id = ${shopId} union all select * from hotgoods where id = ${shopId} union all select * from recommendgoods where id = ${shopId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	}
})
//客户点击商家查看分类商家商品
router.post('/api/getStoreShopItem', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let type = req.body.type
	let shopId = req.body.shopId
	let storeName = req.body.storeName
	connection.query(`select * from discountgoods where id = ${shopId} union all select * from hotgoods where id = ${shopId} union all select * from recommendgoods where id = ${shopId}`,function(err,result){
		let dataList = []
		result.forEach((item,index)=>{
			if(item.id == shopId && item.type == type){
				dataList.push(item)
			}
		})
		res.send({
			code:0,
			succecc:true,
			data:dataList
		})
	})
})
// 用户商品列表
router.post('/api/selectGoods', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let type = req.body.type
	let shopId = req.body.shopId
	let storeName = req.body.storeName
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from discountgoods where uId = ${userId} union all select * from hotgoods where uId = ${userId} union all select * from recommendgoods where uId = ${userId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 请求不同商品接口
router.post('/api/selectGoodsItem', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let shopType = req.body.type
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from ${shopType} where uId = ${userId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 用户添加商品
router.post('/api/addGoods', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	// 商品信息
	let storeObj = req.body.storeObj; 
	// 商品图片
	let imageValue = req.body.imageValue;
	// 用户信息
	let userInfo = req.body.userInfo;
	// 商品类型;
	let shopType = req.body.shopType;
	
	let value = req.body.value;
	
	let type = req.body.type

	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`insert into ${type}(imgUrl,name,pprice,oprice,sale,reportory,delivery,text,detialImgUrl01,detialImgUrl02,detialImgUrl03,bigImage01,bigImage02,bigImage03,storeName,uId,type)values('${imageValue[0].imgUrl}','${storeObj.name}','${storeObj.pprice}','${storeObj.oprice}','0','${storeObj.reportory}','${storeObj.delivery}','${storeObj.text}','${imageValue[1].imgUrl}','${imageValue[2].imgUrl}','${imageValue[3].imgUrl}','${imageValue[4].imgUrl}','${imageValue[5].imgUrl}','${imageValue[6].imgUrl}','${userInfo.nickName}','${userId}','${type}')`,function(err,result){
			res.send({
				code:0,
				success:true,
				data:result
			})
		})
	})
})
// 添加评论数据：
router.post('/api/addContentData', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let goodsArr = req.body.goods
	
	// / 获取当前日期
	var date = new Date();
	 
	// 获取当前月份
	var nowMonth = date.getMonth() + 1;
	 
	// 获取当前是几号
	var strDate = date.getDate();
	 
	// 添加分隔符“-”
	var seperator = "";
	 
	// 对月份进行处理，1-9月在前面添加一个“0”
	if (nowMonth >= 1 && nowMonth <= 9) {
	   nowMonth = "0" + nowMonth;
	}
	 
	// 对月份进行处理，1-9号在前面添加一个“0”
	if (strDate >= 0 && strDate <= 9) {
	   strDate = "0" + strDate;
	}
	 
	// 最后拼接字符串，得到一个格式为(yyyy-MM-dd)的日期
	var nowDate = date.getFullYear() + seperator + nowMonth + seperator + strDate;
	
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		goodsArr.forEach((items,index)=>{
			console.log(items);
			if(items.comment == '') items.comment = '美好的食物总是万里挑一'
			connection.query(`insert into goods_review (userName,time,shopId,uId,content,userImg,type,commentImage,orderId)values('${items.userName}','${nowDate}','${items.goods_id}','${userId}','${items.comment}','${items.headImg}','${items.type}','${items.eval_img}','${items.orderId}')`,function(err,result){
				// 评价成功之后 修改订单状态为6,表示已经评价 
				connection.query(`select * from store_order where uId = ${userId} and order_id = ${items.orderId}`,function(err,result){
					//订单的id
					let id = result[0].id;
					connection.query(`update store_order set order_status = replace(order_status,'4','6') where id = ${id}`,function(){
					})
				})
			})
		})
		res.send({
			data:{
				code:200,
				success:true
			}
		})
	})
})

// 获取评论数据
router.post('/api/ContentData', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let id = req.body.id
	let type = req.body.type
	
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from goods_review where shopId = ${id} and type=${type}`,function(err,result){
			res.send({
				code:0,
				success:true,
				data:result
			})
		})
	})
})
// 取消收藏
router.post('/api/deleteCollect', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let id = req.body.id
	let shopType = req.body.type
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`update goods_collect set status = replace(status,'1','0') where shopId = ${id} and uId = ${userId}`,function(er,resu){
			connection.query(`delete from goods_collect where uId = ${userId} and shopId = ${id} and type = '${shopType}'`,function(err,result){
				res.send({
					code:0,
					succecc:true,
					data:result
				})
			})
		})
	})
})
// 添加收藏
router.post('/api/addCollect', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	let shopData = req.body.shopData;
	
	let shopType = req.body.shopType
	
	// status  :1 说明该商品已经添加
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`insert into goods_collect (imgUrl,name,pprice,oprice,sale,uId,shopId,type,status) values ('${shopData.imgUrl}','${shopData.name}','${shopData.pprice}','${shopData.oprice}','${shopData.sale}','${userId}','${shopData.id}','${shopType}','1')`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 获取我的收藏数据
router.post('/api/getCollectGoods', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let status = req.body.status
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from goods_collect where uId = ${userId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 删除；收藏数据
router.post('/api/deleteCollectGoods', function(req, res, next) {
	let goodsId = req.body.goodsId;
	for(var i=0;i<goodsId.length;i++){
		connection.query(`delete from goods_collect where shopId=${goodsId[i]}`,function(e,r){
			res.json({
				data:{
					success:true
				}
			})
		})
	}
})
// 添加最近浏览数据
router.post('/api/addGoodsBrowse', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let status = req.body.status;
	
	let imgUrl = req.body.imgUrl;
	let name = req.body.name;
	let pprice = req.body.pprice;
	let oprice = req.body.oprice;
	let sale = req.body.sale;
	let shopId = req.body.id
	let shopType = req.body.shopType
	let user_id = req.body.userId
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from goods_browse`,function(err,result){
			let AddSql = `insert into goods_browse (imgUrl,name,pprice,oprice,sale,uId,shopId,type) values ('${imgUrl}','${name}','${pprice}','${oprice}','${sale}','${userId}','${shopId}','${shopType}')`
			// connection.query(AddSql,function(er,resu,filed){
			// 	// res.send({
			// 	// 	code:0,
			// 	// 	succecc:true,
			// 	// 	data:resu
			// 	// })
			// })
			let sql = `inster into goods_browse(imgUrl)`
			connection.query(sql,`'${imgUrl}'`,function(err,result){
				console.log(result);
			})
		})
	})
})
// 获取最近浏览数据
router.post('/api/getBrowseGoods', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	
	let status = req.body.status
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from goods_browse where uId = ${userId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 删除；浏览数据
router.post('/api/deleteBrowseGoods', function(req, res, next) {
	let goodsId = req.body.goodsId;
	for(var i=0;i<goodsId.length;i++){
		connection.query(`delete from goods_browse where shopId=${goodsId[i]}`,function(e,r){
			res.json({
				data:{
					success:true
				}
			})
		})
	}
})
// 请求待付款 带配送 待评价数据  状态为1
router.post('/api/getOrderItem', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	// 订单状态
	let status = req.body.status
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from store_order where uid = ${userId} and order_status =${status} `,function(err, result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 请求全部订单数据
router.post('/api/getAllOrder', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from store_order where uid = ${userId}`,function(err, result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
	})
})
// 请求全部订单具体商品信息数据
router.post('/api/getOrderData', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from store_order where uid = ${userId}`,function(err, result){
			let orderId = result[0].order_id
			connection.query(`select * from orderData where userId = ${userId}`,function(er,re){
				res.send({
					code:0,
					succecc:true,
					data:re
				})
			})
		})
	})
})
// 请求订单详情商品信息数据
router.post('/api/getOrderDetialData', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	let orderId = req.body.orderId;
	connection.query(`select * from user where phone = ${phone.name}`,function(error, results, fields){
		let userId = results[0].id
		connection.query(`select * from orderData where order_id = '${orderId}' and userId = ${userId}`,function(err,result){
			res.send({
				code:0,
				succecc:true,
				data:result
			})
		})
		
	})
})
//支付接口
router.post('/api/payment', function(req, res, next) {
    //接收前端给后端的订单号
    let orderId = req.body.orderId;
	
	//总价
	let price = req.body.price;
	//商品名称 join 将数组中的元素转换为字符转
	let list = req.body.list.join('');
    
    const formData = new AlipayFormData();
    //调用get方法
    formData.setMethod('get'),
    //支付时 的信息
    formData.addField('bizContent', {
      outTradeNo: orderId,//订单号
      productCode: 'FAST_INSTANT_TRADE_PAY',//写死的
      totalAmount: price,//金额
      subject: list//商品名称
    });
    //支付成功或者失败打开的页面
    formData.addField('returnUrl', 'http://192.168.10.1:8080/#/pages/payment-success/payment-success');
    const result = alipaySdk.exec(
      'alipay.trade.page.pay',
      {},
      { formData: formData },
    );
    result.then(resp=>{
        res.send({
            data:{
                code:200,
                success:true,
                paymentUrl:resp
            }
        })
    })
});
// 删除订单
router.post('/api/deleteOrder', function(req, res, next) {
    let token = req.headers.token;
    let phone = jwt_decode(token);
	//订单号
	let orderId = req.body.orderId;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
			//订单的id
			let id = result[0].id;
			connection.query(`delete from store_order where order_id = ${orderId} and id = ${id}`,function(er,resul){
				connection.query(`delete from orderData where order_id = ${orderId} and userId = ${userId}`,function(e,r){
					res.send({
						data:{
							code:200,
							success:true
						}
					})
				})
			})
		})
	})
});
// 确认收货
router.post('/api/confirmReceipt', function(req, res, next) {
    let token = req.headers.token;
    let phone = jwt_decode(token);
	//订单号
	let orderId = req.body.orderId;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
			//订单的id
			let id = result[0].id;
			connection.query(`update store_order set order_status = replace(order_status,'3','4') where id = ${id}`,function(){
				res.send({
					data:{
						code:200,
						success:true
					}
				})
			})
		})
	})
})
// 配送
router.post('/api/delivery', function(req, res, next) {
    let token = req.headers.token;
    let phone = jwt_decode(token);
	//订单号
	let orderId = req.body.orderId;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
			//订单的id
			let id = result[0].id;
			connection.query(`update store_order set order_status = replace(order_status,'2','3') where id = ${id}`,function(){
				res.send({
					data:{
						code:200,
						success:true
					}
				})
			})
		})
	})
});
// 取消订单
router.post('/api/cancleOrder', function(req, res, next) {
    let token = req.headers.token;
    let phone = jwt_decode(token);
	//订单号
	let orderId = req.body.orderId;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
			//订单的id
			let id = result[0].id;
			connection.query(`update store_order set order_status = replace(order_status,'2','5') where id = ${id}`,function(){
				res.send({
					data:{
						code:200,
						success:true
					}
				})
			})
		})
	})
});
// 付款 修改订单状态
router.post('/api/submitOrder', function(req, res, next) {
    let token = req.headers.token;
    let phone = jwt_decode(token);
	//订单号
	let orderId = req.body.orderId;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
			//订单的id
			let id = result[0].id;
			connection.query(`update store_order set order_status = replace(order_status,'1','2') where id = ${id}`,function(){
				res.send({
					data:{
						code:200,
						success:true
					}
				})
			})
		})
	})
})
// 生成订单
router.post('/api/addOrder', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	//前端给后端传递的数据订单id
	let goodsArr = req.body.arr;
	
	let type = req.body.type
	
	let addressId = req.body.addressId
	
	let userPhone = req.body.userPhone
	
	// 补零
	function setTimeDateFmt(s){
		return s , 10 ? '0' + s : s;
	}
	//生成订单号
	function orderNumber(){
		const now = new Date(); //时间戳
		let fullYear = now.getFullYear(); //年
		let month = setTimeDateFmt( now.getMonth() + 1 ); //月
		let day = setTimeDateFmt( now.getDate() );//日
		let hour = setTimeDateFmt( now.getHours() );//时
		let minutes = setTimeDateFmt( now.getMinutes() ); //分
		let seconds = setTimeDateFmt( now.getSeconds() );//秒
		// 订单号
		let orderCode = fullYear + month + day + hour + minutes + seconds + ( Math.round( Math.random() * 1000000 ));
		return orderCode;
	}
	function createTimeFn(){
		const now = new Date(); //时间戳
		let fullYear = now.getFullYear(); //年
		let month = setTimeDateFmt( now.getMonth() + 1 ); //月
		let day = setTimeDateFmt( now.getDate() );//日
		let hour = setTimeDateFmt( now.getHours() );//时
		let minutes = setTimeDateFmt( now.getMinutes() ); //分
		let seconds = setTimeDateFmt( now.getSeconds() );//秒
		// 订单号
		let time = fullYear +'-'+ month +'-'+ day +'-'+ hour +'-'+ minutes +'-'+ seconds 
		return time;
	}
	// 商品名称
	let goodsName = [];
	// 订单总价
	let goodsPrice = 0;
	// 订单商品总数量
	let goodsNum = 0;
	//订单号
	let orderId = orderNumber();
	// 下单日期
	let createTime = createTimeFn()
	// 商品id
	let shopid = [];
	// 订单图片
	let goodsImgUrl = [];
	// 商品单价列表按
	let unitPrice = [];
	let total = 0;
	goodsArr.forEach(v=>{
		shopid.push(v.id)
		goodsName.push(  v.name );
		goodsNum += parseInt(v.num);
		goodsPrice +=  v.num * v.pprice;
		goodsImgUrl.push(v.imgUrl);
		unitPrice.push(goodsPrice)
		total = goodsPrice
	})
	
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		let storeName = results[0].nickName;
		let phone = results[0].phone;
		// 将订单写入到数据库中
		connection.query(`insert into store_order (uId,order_id,order_status,type,storeName,address_id,phone,createTime,unitPrice) values ('${userId}','${orderId}','1','${type}','${storeName}','${addressId}','${phone}','${createTime}','${total}')`,function(error,results){
			goodsArr.forEach((item,index)=>{
				console.log(item);
				connection.query(`insert into orderData (order_id,shopId,type,goods_price,goods_num,goods_name,imgUrl,userId,storeName) values ('${orderId}','${item.goods_id}','${item.type}','${item.pprice}','${item.num}','${item.name}','${item.imgUrl}','${userId}','${item.name}')`,function(er,re){
					
				})
				// shopid.forEach((i)=>{
				// connection.query(`delete from goods_cart where id = ${item.id}`,function(){
					
				// })
				// })
			})
		})
		// 根据用户id 和订单号查询订单
		connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(err,result){
			res.send({
				data:{
					code:200,
					success:true,
					data:result
				}
			})
		})
		
	})
})

// 直接购买生成订单
router.post('/api/addOrderByNow', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	// 前端提交的数据
	let goods_id = req.body.id;
	let name = req.body.name;
	let imgUrl = req.body.imgUrl;
	let pprice = req.body.pprice;
	let type = req.body.shopType
	let num = req.body.num
	function setTimeDateFmt(s){
		return s , 10 ? '0' + s : s;
	}
	//生成订单号
	function orderNumber(){
		const now = new Date(); //时间戳
		let fullYear = now.getFullYear(); //年
		let month = setTimeDateFmt( now.getMonth() + 1 ); //月
		let day = setTimeDateFmt( now.getDate() );//日
		let hour = setTimeDateFmt( now.getHours() );//时
		let minutes = setTimeDateFmt( now.getMinutes() ); //分
		let seconds = setTimeDateFmt( now.getSeconds() );//秒
		// 订单号
		let orderCode = fullYear + month + day + hour + minutes + seconds + ( Math.round( Math.random() * 1000000 ));
		return orderCode;
	}
	// 订单号
	let orderId = orderNumber()
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		let storeName = results[0].nickName
		connection.query(`insert into store_order (uId,order_id,goods_name,goods_price,goods_num,order_status,imgUrl,unitPrice,shopId,type,storeName) values ('${userId}','${orderId}','${name}','${pprice}','${parseInt(num)}','1','${imgUrl}','${pprice}','${goods_id}','${type}','${storeName}')`,function(err,result){
			// 根据用户id 和订单号查询订单
			connection.query(`select * from store_order where uId = ${userId} and order_id = ${orderId}`,function(er,resu){
				res.send({
					code:0,
					success:true,
					data:resu
				})
			})
		})
	})
})

// 加入购物车
router.post('/api/addCart', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	//商品id
	let goods_id = req.body.goods_id;
	//用户输入的商品数量
	let num = req.body.num;
	// 商品类型
	let shopType = req.body.shopType;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		let userId = results[0].id;
		connection.query(`select * from ${shopType} where id = ${goods_id}`, function (err, result) {
			let name = result[0].name;
			let imgUrl = result[0].imgUrl;
			let pprice = result[0].pprice;
			//查询当前用户之前是否添加过这个商品
			// 根据用户id  和 商品id 查询商品信息 ，判断是否有添加过该商品
			connection.query(`select * from goods_cart where uId = ${userId} and goods_id = ${goods_id}`, function (err, data) {
				if(data.length > 0){
					//如果当前用户已经添加过本商品,就让数量增加
					connection.query(`update goods_cart set num = replace(num,${data[0].num},${ parseInt(num) + parseInt(data[0].num) }) where id = ${data[0].id}`, function (e, r) {
						res.json({
							data:{
								success:"加入成功"
							}
						})
					})
				}else {
					//如果当前用户之前没有加入过本商品,需要添加进入
					connection.query('insert into goods_cart (uId,goods_id,name,imgUrl,pprice,num,type) values ("'+userId+'","'+goods_id+'","'+name+'","'+imgUrl+'","'+pprice+'","'+num+'","'+shopType+'")', function (err, data) {
						res.json({
							data:{
								success:"加入成功"
							}
						})
					})
				}
			})
		})
	})
})
	//删除购物车商品
router.post('/api/deleteCart', function(req, res, next) {
	let goodsId = req.body.goodsId;
	for(var i=0;i<goodsId.length;i++){
		connection.query(`delete from goods_cart where id=${goodsId[i]}`,function(e,r){
			res.json({
				data:{
					success:true
				}
			})
		})
	}
})
//1. 当前用户
//2. 当前用户--->哪一个商品的数量发展变化  [查询]   原来的数量
//3. 替换 ===> 把前端给的值拿过来, 把原来数量替换掉

//修改当前用户购物车商品数量
router.post('/api/updateNumCart', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	//商品id
	let goodsId = req.body.goodsId;
	//用户输入的商品数量
	let num = req.body.num;
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from goods_cart where uId = ${userId} and goods_id = ${goodsId}`, function (err, result) {
			//数据中当前的数量
			let goods_num = result[0].num;
			//当前的id号
			let id = result[0].id;
			//修改[替换]
			connection.query(`update goods_cart set num = '${num}' where id = ${id}`, function (e, r) {
				res.json({
					data:{
						success:true
					}
				})
			})
		})
		
	})
})
//获取当前用户购物车列表
router.post('/api/selectCart', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token);
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		//当前用户id
		let userId = results[0].id;
		connection.query(`select * from goods_cart where uId = ${userId}`, function (err, result) {
			res.json({
				data:result
			})
		})
	})
})
//当前用户修改收货地址
router.post('/api/updateAddress', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token) //解析token 拿到用户信息账号
	let name = req.body.name;
	let tel = req.body.tel;
	let province = req.body.province;
	let city = req.body.city;
	let district = req.body.district;
	let address = req.body.address;
	let isDefault = req.body.isDefault;
	let id = req.body.id;
	//获取userId
	connection.query(`select * from user where phone = ${phone.name}`, function (error, results, fields) {
		let userId = results[0].id;
		connection.query(`select * from address where userId = ${userId}`, function (err, result) {
			let childId = result[0].id;
			// 将isDefault值为1 的替换成为 0
			connection.query(`update address set isDefault = replace(isDefault,"1","0") where id = ${childId}`, function (e, r) {
				let updateSql = `update address set name = ?,tel = ?,province = ?,city = ?,district = ?,address = ?,isDefault = ?,userId = ? where id = ${id}`
				connection.query(updateSql,[name,tel,province,city,district,address,isDefault,userId],function (err, result) {
					res.send({
						data:{
							success:true,
							msg:'地址修改成功'
						}
					})
				})
			})
		})
	})
})
// 删除用户地址
router.post('/api/deletAddress', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token); //解析token 拿到用户信息账号
	
	let addressId = req.body.addressId
	connection.query(`select * from user where phone = ${phone.name}`,function(erroe,results,fields){
		let id = results[0].id;
		connection.query(`delete from address where userId = ${id} and id = ${addressId}`,function(err,result){
			res.send({
				code:0,
				success:true,
				data:result
			})
		})
	})
})
//当前用户新增地址
router.post('/api/addAddress', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token) //解析token 拿到用户信息账号
	let name = req.body.name;
	let tel = req.body.tel;
	let province = req.body.province;
	let city = req.body.city;
	let district = req.body.district;
	let address = req.body.address;
	let isDefault = req.body.isDefault;
	connection.query(`select * from user where phone = ${phone.name}`,function(erroe,results,fields){
		let id = results[0].id;
		let sqlInert = 'insert into address (name,tel,province,city,district,address,isDefault,userId) values ("'+name+'","'+tel+'","'+province+'","'+city+'","'+district+'","'+address+'","'+isDefault+'","'+id+'")';
		connection.query(sqlInert,function(err, result, field){
			res.send({
				data:{
					success:true,
					msg:'新增地址成功'
				}
			})
		})
	})
})
//当前用户查询收货地址
router.post('/api/selectAddress', function(req, res, next) {
	let token = req.headers.token;
	let phone = jwt_decode(token)
	connection.query(`select * from user where phone = ${phone.name}`,function(erroe,results,fields){
		let id = results[0].id;
		connection.query(`select * from address where userId = ${id}`,function(err, result, field){
			res.send({
				data:result
			})
		})
	})
})
// 订单详情获取订单地址
router.post('/api/getAddressItem', function(req, res, next) {
	let addressId = req.body.addressId;
	let userId = req.body.userId
	connection.query(`select * from address where userId = '${userId}' and id = '${addressId}'`,function(error,results){
		res.send({
			code:0,
			succecc:true,
			data:results
		})
	})
})
//注册验证手机号是否存在
router.post('/api/registered', function(req, res, next) {
	
	//前端给后端的数据
	let params = {
		uesrTel : req.body.phone
	};
	//查询手机号是否存在
	connection.query( user.queryUserCount( params ) , function (error, results, fields) {
		if( results.length > 0 ){
			res.send({
				data:{
					success:false,
					msg:"手机号已经存在",
				}
			})
		}else{
			res.send({
				data:{
					success:true
				}
			})
		}
	})
	return;
})

// 我的 订单状态图片 页面数据
router.get('/api/my/orderStatusList', function(req, res, next) {
	res.json({
		code:0,
		succecc:true,
		msg:'请求成功',
		data:{
			orderStatusData:[
				{name:'待付款',Image:'../../static/image/icon/fukuan.png'},
				{name:'待配送',Image:'../../static/image/icon/yunshupeisong.png'},
				{name:'待收货',Image:'../../static/image/icon/daishouhuo.png'},
				{name:'待评价',Image:'../../static/image/icon/xiaoxizhongxin.png'},
			],
		}
	})
})
// 我的 列表 页面数据
router.get('/api/my/myList', function(req, res, next) {
	res.json({
		code:0,
		succecc:true,
		msg:'请求成功',
		data:{
			bottomDataList:[
				{name:'全部订单',leftImage:'../../static/image/icon/dingdan.png',rightImage:'../../static/image/icon/arrow-right.png'},
				{name:'收藏商品',leftImage:'../../static/image/icon/jushoucang.png',rightImage:'../../static/image/icon/arrow-right.png'},
				{name:'地址管理',leftImage:'../../static/image/icon/dizhiguanli.png',rightImage:'../../static/image/icon/arrow-right.png'},
				{name:'最近浏览',leftImage:'../../static/image/icon/zuijinliulan.png',rightImage:'../../static/image/icon/arrow-right.png'},
				{name:'我的店铺',leftImage:'../../static/image/icon/mystore.png',rightImage:'../../static/image/icon/arrow-right.png'},
			]
		}
	})
})

// 商品分类数据
router.get('/api/list/getListData', function(req, res, next) {
	connection.query(`select * from First_list`,function(erroe,results,fields){
		res.send({
			code:0,
			succecc:true,
			data:results
		})
	})
});

// 首页轮播图
router.get('/api/index/BannerData', function(req, res, next) {
	res.json({
		"code": 0,
		"message": "successful",
		data:[
			{imgUrl: "../../static/image/indexImage/banner01.png"},
			{imgUrl: "../../static/image/indexImage/banner02.png"}
		]
	})
});

// 首页分类图
router.get('/api/index/list', function(req, res, next) {
	res.json({
		"code": 0,
		"message": "successful",
		data:[
			{imgUrl:"/static/image/indexImage/个人护理.png",name:"个人护理"},
			{imgUrl:"/static/image/indexImage/家用电器.png",name:"家用电器"},
			{imgUrl:"/static/image/indexImage/生鲜水果.png",name:"生鲜水果"},
			{imgUrl:"/static/image/indexImage/休闲零食.png",name:"休闲零食"},
			{imgUrl:"/static/image/indexImage/营养奶品.png",name:"营养奶品"},
			{imgUrl:"/static/image/indexImage/母婴用品.png",name:"母婴用品"},
			{imgUrl:"/static/image/indexImage/进口好货.png",name:"进口好货"},
			{imgUrl:"/static/image/indexImage/家居清洁.png",name:"家居清洁"},
			{imgUrl:"/static/image/indexImage/文具体育.png",name:"文具体育"},
			{imgUrl:"/static/image/indexImage/粮油厨房.png",name:"粮油厨房"}
		]
	})
});

// 获取分类二级分类数据
router.get('/api/list/getListDataItem', (req, res, next) => {
	let itemId = req.query.id
	connection.query(`select * from second_list where first_id = ${itemId}`,function(error,results){
		res.send({
			code:0,
			success:true,
			data:results
		})
	})
})
module.exports = router;
